package com.gpay.erp.web.control;

import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.NoteType;
import com.gpay.erp.core.system.bean.PayType;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.core.system.bean.WareHouse;
import com.gpay.erp.services.common.GlobalStatus;
import com.gpay.erp.services.common.PaytypeService;
import com.gpay.erp.services.common.impl.StringUtil;
import com.gpay.erp.services.common.impl.SystemConstant;
import com.gpay.erp.services.purchase.*;
import com.gpay.erp.services.purchase.bean.*;
import com.gpay.erp.services.storage.MandanService;
import com.gpay.erp.services.storage.StorageService;
import com.gpay.erp.services.storage.StorageSubService;
import com.gpay.erp.services.storage.bean.Mandan;
import com.gpay.erp.services.storage.bean.Storage;
import com.gpay.erp.services.storage.bean.StorageSub;
import com.gpay.erp.web.util.Arith;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.PaymentOrderMode;
import com.gpay.erp.web.vo.ResponseInfo;
import com.gpay.erp.web.vo.StorageMode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by wuzonghui on 15/11/5.
 * 入库控制类
 */
@Controller
@RequestMapping("/storage/")
public class StorageController extends BaseController {
    private Log logger = LogFactory.getLog(ApplicationController.class);
    @Autowired
    private StorageService storageService;
    @Autowired
    private MandanService mandanService;
    @Autowired
    private GlobalStatus globalStatus;

    @Autowired
    private StorageSubService storageSubService;

    @Autowired
    private MessageSource messageSource;
    @Autowired
    private PaytypeService paytypeService;
    @Autowired
    private ContractSubService contractSubService;
    @Autowired
    private ContractService contractService;

    private String result =""; //页面返回错误码
    private String message = ""; //页面返回信息

    // 页面跳转 入库管理
    @RequestMapping("bePutInStorageList")
    public String bePutInStorageList() {
        return "storage/bePutInStorageList";
    }

    // 页面跳转 生成入库单
    @RequestMapping("bePutInStorageDocAdd")
    public String bePutInStorageDocAdd(String id, ModelMap modelMap) {
        modelMap.addAttribute("contractSubId", id);
        return "storage/bePutInStorageDocAdd";
    }

    // 页面跳转 入库单list页面
    @RequestMapping("storageDocList")
    public String storageDocList() {
        return "storage/storageDocList";
    }

    // 页面跳转 入库单调整
    @RequestMapping("storageDocEdit")
    public String storageDocEdit(String id, ModelMap modelMap) {
        modelMap.addAttribute("storageId", id);
        return "storage/storageDocEdit";
    }

    // 页面跳转 入库单明细
    @RequestMapping("storageDocView")
    public String storageDocView(String id, ModelMap modelMap) {
        modelMap.addAttribute("storageId", id);
        return "storage/storageDocView";
    }


    /**
     * 查询仓库信息
     *
     * @param request
     * @param response
     */
    @RequestMapping("warehouse")
    public void warehouse(HttpServletRequest request,
                          HttpServletResponse response) {
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setResult("00000");
        responseInfo.setMessage(messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA));
        WareHouse wareHouse = new WareHouse();
        List<WareHouse> wareHouses = paytypeService.selectListWarehouse();
        responseInfo.setObject(wareHouses);
        WebUtil.responseToJson(response, responseInfo);

    }

    /**
     * 查询捆包号是否重复
     *
     * @param request
     * @param response
     */
    @RequestMapping("doublePackage")
    public void doublePackage(String packageNumber, HttpServletRequest request,
                              HttpServletResponse response) {
        ResponseInfo responseInfo = new ResponseInfo();
        String result = "00000";
        responseInfo.setMessage(messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA));
        List<StorageSub> storageSubs = storageSubService.selectByPackageNumber(packageNumber);
        if (storageSubs.size() > 0) {
            result = "00011";
        }
        responseInfo.setResult(result);
        responseInfo.setObject(storageSubs);
        WebUtil.responseToJson(response, responseInfo);

    }

    /**
     * 入库新增
     *
     * @param contractSubId 合同子项contractSubId
     */
    @RequestMapping("selectStorage")
    public void selectStorage(String contractSubId,
                              HttpServletRequest request, HttpServletResponse response) {
        logger.info("selectStorage start contractSubId:" + contractSubId);
        result = "00010";
        message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        Storage storage = new Storage();
        ResponseInfo responseInfo = new ResponseInfo();
        List<StorageSub> storageSubs = new ArrayList<StorageSub>();
        if (!"".equals(contractSubId) || null != contractSubId) {
            ContractSub contractSub = contractSubService.selectById(contractSubId);
            if (SystemConstant.CONTRACTSTATUSEXEU.equals(contractSub.getStatusSub())) { //子项执行状态
                storage.setProviderName(contractSub.getProviderName());
                storage.setGoodsName(contractSub.getGoodsName());
                storage.setCpspecification(contractSub.getCpspecification());
                storage.setMarks(contractSub.getMarks());
                storage.setCdName(contractSub.getCdName());
                storage.setStandards(contractSub.getStandards());
                storage.setQualityGrade(contractSub.getQualityGrade());
                storage.setStorageNumber(contractSub.getStorageNumber());
                storage.setResourceNumber(contractSub.getResourceNumber());
                storage.setContractSubCode(contractSub.getSubContractCode());

            } else {
                result = "00011";
                message = messageSource.getMessage("application.service.fail",
                        new Object[]{}, Locale.CHINA);
            }
        }
        StorageMode storageMode = new StorageMode();
        storageMode.setStorage(storage);
        logger.info("selectStorage end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(storageMode);
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * @param storageMode
     * @param request
     * @param response
     */
    @RequestMapping("saveStorageSub")
    public void saveStorageSub(@RequestBody StorageMode storageMode,
                               HttpServletRequest request, HttpServletResponse response) {
        logger.info("saveStorageSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int insertId = 1;
//        String mandanCode = mandanService.getMandanCode(); //码单号
        String storageCode = storageService.getStorageCode();//入库号
        result = "00010";
        message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        Object object = "1";

        if (null != storageMode) {
            Storage storage = storageMode.getStorage();
            String status = SystemConstant.CONTRACTSTATUSEXEU ;//默认执行状态
            if (storage.isFlagFinish()) {  //入库是否收货完成
                status = SystemConstant.CONTRACTSTATUSGOODSFINISH;
            }
            ContractSub contractSub = contractSubService.selectById(storage.getF_contractSubId());

//            storage.setStorageMdCode(mandanCode);
            storage.setContractSubCode(contractSub.getSubContractCode());
            storage.setContractCode(contractSub.getContractNumber());
            storage.setStorageCode(storageCode);
            storage.setAccountName(sysUser.getAccountName());
            storage.setF_account(sysUser.getF_account());
            storage.setStorageStatus(SystemConstant.STORAGESTATUSCONFIRM);

            contractSub.setStorageNumber(Arith.add(contractSub.getStorageNumber(), storage.getStorageWeight()));
            contractSub.setStatusSub(status);
            List<StorageSub> storageSubs = storageMode.getStorageSubs();
            int count = 1;
            for (StorageSub storageSub : storageSubs) { //组织入库子项表
                storageSub.setStorageSubCode(storageCode + StringUtil.getFormatNumber(String.valueOf(count)));
                count++;
                storageSub.setContractSubStatus(status);
                storageSub.setPurchasePrice(0.0);
                storageSub.setStorageSubStatus(SystemConstant.STORAGESTATUSCONFIRM);
                storageSub.setContractCode(contractSub.getContractNumber());
                storageSub.setAccountName(sysUser.getAccountName());
                storageSub.setF_account(sysUser.getF_account());

                storageSub.setWarehouseCode(storage.getWarehouseCode());
                storageSub.setWarehouseName(storage.getWarehouseName());
                storageSub.setGoodsName(storage.getGoodsName());
                storageSub.setMarks(storage.getMarks());
                storageSub.setCpspecification(storage.getCpspecification());
                storageSub.setCdName(storage.getCdName());
                storageSub.setQualityGrade(storage.getQualityGrade());
                storageSub.setStandards(storage.getStandards());


            }
            insertId = storageService.saveStorageSubs(storage, storageSubs, contractSub);
            if (insertId == 1) {
                result = "00011";
                message = messageSource.getMessage("add.fail",
                        new Object[]{}, Locale.CHINA);
                ;
            }
        }

        logger.info("saveStorageSub end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(storageMode);
        WebUtil.responseToJson(response, responseInfo);
    }



    /**
     * 采购入库调整查询
     *
     * @param storage  库存信息
     * @param request
     * @param response
     */
    @RequestMapping("selectAdjustmentStorageList")
    public void selectAdjustmentStorageList(Storage storage, PageHelper pageHelper,
                                            HttpServletRequest request, HttpServletResponse response) {
        logger.info("selectAdjustmentStorageList start contractSubId:");
        result = "00010";
        message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        ResponseInfo responseInfo = new ResponseInfo();
        if ("".equals(pageHelper.getOrder()) || null == pageHelper.getOrder()) {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        storage.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        storage.setToRow(pageHelper.getPage() * pageHelper.getRows());
        storage.setSort(pageHelper.getSort());
        storage.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = storageService.selectPageList(storage);
        if (pagerModel != null) {
            for (Object hashMap1 : pagerModel.getRows()) {
                Storage hashMap = (Storage) hashMap1;
                String statusCode = globalStatus.getStorageStatus(Integer.parseInt(hashMap.getStorageStatus()));
                hashMap.setStorageStatus(statusCode);

            }
            logger.info("selectAdjustmentStorageList end");
            responseInfo.setResult(result);
            responseInfo.setMessage(message);
            responseInfo.setObject(pagerModel);
            WebUtil.responseToJson(response, responseInfo);
        }
    }

    /**
     * 采购入库明细查询
     * @param storageId 库存id
     * @param request
     * @param response
     */
    @RequestMapping("selectStorageSubList")
    public void selectStorageSubList(String storageId,
                                     HttpServletRequest request, HttpServletResponse response) {
        logger.info("selectStorageSubList start contractSubId:");
        String result = "00010";
        String message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        ResponseInfo responseInfo = new ResponseInfo();
        StorageMode storageMode = new StorageMode();

        Storage storage = storageService.selectById(storageId);
        List<StorageSub> storageSubs = storageSubService.selectByFId(storageId);
        for (StorageSub storageSub:storageSubs) {
            String statusCode = globalStatus.getStorageStatus(Integer.parseInt(storageSub.getStorageSubStatus()));
            String contractSubStatus = globalStatus.getContractStatus(Integer.parseInt(storageSub.getContractSubStatus()));
            storageSub.setContractSubStatus(contractSubStatus);
            storageSub.setStorageSubStatus(statusCode);
        }
        storageMode.setStorage(storage);
        storageMode.setStorageSubs(storageSubs);
        logger.info("selectStorageSubList end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(storageMode);
        WebUtil.responseToJson(response, responseInfo);
    }
    /**
     * 入库单撤销 按钮
     * @param storageId 库存id
     * @param request
     * @param response
     */
    @RequestMapping("deleteStorageSubList")
    public void deleteStorageSubList(String storageId,
                                     HttpServletRequest request, HttpServletResponse response) {
        logger.info("deleteStorageSubList start:");
        result = "00010";
        message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        ResponseInfo responseInfo = new ResponseInfo();

        Storage storage = storageService.selectById(storageId);
        List<StorageSub> storageSubs = storageSubService.selectByFId(storageId);
        if (SystemConstant.STORAGESTATUSCONFIRM.equals(storage.getStorageStatus())) {
            storage.setStorageStatus(SystemConstant.STORAGESTATUSCANCEL);
            for (StorageSub storageSub:storageSubs) {
                storageSub.setStorageSubStatus(SystemConstant.STORAGESTATUSCANCEL); //入库子项状态
                storageSub.setContractSubStatus(SystemConstant.CONTRACTSTATUSEXEU); //合同状态执行
            }

            if (checkMandanStatus(storageId)) {

                ContractSub contractSub = contractSubService.selectById(storage.getF_contractSubId());  //修改合同子项信息
                contractSub.setStatusSub(SystemConstant.CONTRACTSTATUSEXEU);
                Double sn = contractSub.getStorageNumber();
                contractSub.setStorageNumber(Arith.sub(sn,storage.getStorageWeight()));

                List<ContractSub> contractSubs = contractSubService.selectByFidAndStatus(contractSub);
                Contract contract = contractService.selectById(contractSub.getF_id());
//                if(contractSubs.size()==0){
                    contract.setContractStatus(SystemConstant.CONTRACTSTATUSEXEU);
//                }
                int updateId = storageService.deleteStorageSubList(storage,storageSubs,contractSub,contract);
            }


        }else {
            result = "00011";
            message ="撤销状态不能撤销";
        }
        logger.info("deleteStorageSubList end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject("1");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 调整入库单 保存 按钮
     * @param storageMode
     * @param request
     * @param response
     */
    @RequestMapping("updateStorageSubList")
    public void updateStorageSubList(@RequestBody StorageMode storageMode,
                                     HttpServletRequest request, HttpServletResponse response) {
        logger.info("updateStorageSubList start:");
        String result = "00010";
        String message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        ResponseInfo responseInfo = new ResponseInfo();

       String storageId = storageMode.getStorage().getId();
        Storage storage = storageService.selectById(storageId);
        List<StorageSub> storageSubs = storageSubService.selectByFId(storageId);

        if (SystemConstant.STORAGESTATUSCONFIRM.equals(storage.getStorageStatus())) {
            storage.setStorageStatus(SystemConstant.STORAGESTATUSCONFIRM);
            Double storageWeight =0.0;//入库量
            Double storagePage = 0.0;//入库件数
            for (StorageSub storageSub:storageSubs) {
                for (StorageSub storageSub1:storageMode.getStorageSubs()){  //读取当前库存里面的直
                    if (storageSub.getId().equals(storageSub1.getId())) {
                        if (SystemConstant.STORAGESTATUSCONFIRM.equals(storageSub.getStorageSubStatus())) {
                            storageSub.setStoragePage(storageSub1.getStoragePage());
                            storageSub.setStorageNo(storageSub1.getStorageNo());
                        }else {

                            result = "00011";
                            message ="撤销状态不能调整";
                            break;
                        }
                    }
                }
                if (SystemConstant.STORAGESTATUSCONFIRM.equals(storageSub.getStorageSubStatus())) { //统计主表件数,重量
                    storageWeight = Arith.add(storageSub.getStorageNo(),storageWeight);
                    storagePage =Arith.add(storageSub.getStoragePage(),storagePage);
                }

            }
            storage.setStoragePage(storagePage);
            storage.setStorageWeight(storageWeight);
            if (checkMandanStatus(storageId)) {

                ContractSub contractSub = contractSubService.selectById(storage.getF_contractSubId());  //修改合同子项信息
//                contractSub.setStatusSub("1");
                contractSub.setStorageNumber(storage.getStorageWeight());

                int updateId = storageService.updateStorageSubList(storage,storageSubs,contractSub);
            }



        }else {
            result = "00011";
            message ="撤销状态不能撤销";
        }
        logger.info("deleteStorageSubList end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject("1");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 撤销子项 按钮
     * @param storageSubIds 库存id
     * @param request
     * @param response
     */
    @RequestMapping("deleteCancelStorageSubList")
    public void deleteCancelStorageSubList(String storageSubIds,
                                     HttpServletRequest request, HttpServletResponse response) {
        logger.info("deleteCancelStorageSubList start:");
        result = "00010";
        message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        ResponseInfo responseInfo = new ResponseInfo();

        String[] storageSubId = storageSubIds.split(",");
        StorageSub storageSub =null;
        for (String subId:storageSubId) {
            storageSub = storageSubService.selectById(subId);
            if (SystemConstant.STORAGESTATUSCONFIRM.equals(storageSub.getStorageSubStatus())) {
                if (checkMandanStatus(storageSub.getF_storageId())) {
                    int updateId = storageService.deleteCancelStorageSubList(storageSubId);
                }
            }else {
                result = "00011";
                message ="已经是撤销状态 不能撤销";
                break;
            }
        }


        logger.info("deleteCancelStorageSubList end");
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject("1");
        WebUtil.responseToJson(response, responseInfo);
    }


    /**
     * 判断码单是否挂牌
     * @param storageId 库存id
     * @return
     */
    public boolean checkMandanStatus(String storageId) {
        boolean flag = true;

        List<Mandan> mandans = mandanService.selectListByFid(storageId);
        for (Mandan mandan:mandans) {
            if("1".equals(mandan.getListFlag())) {
                result = "00011";
                message = "码单号已经挂牌不能撤销";
                flag = false;
                break;
            }else if ("1".equals(mandan.getPackageType())) {
                result = "00011";
                message ="捆包已经封锁不能撤销 请先撤牌";
                flag = false;
                break;
            }
        }
        return flag;
    }
}
